import getApiData from '@/services/cpasRequest';
import { downloadDG, openDG } from '@/services/fileService';
import { message } from 'antd';
import { request } from 'umi';

/**
 * 上传底稿到临时目录
 */
export async function draftManageUploadBatch(formData: FormData) {
  try {
    const response = await request('/cpasApi/draftManage/uploadBatch', {
      method: 'POST',
      data: formData,
      requestType: 'form',
    });
    if (response.ok) {
      console.log('Files uploaded successfully');
      return response.data;
    } else {
      console.error('Failed to upload files');
    }
  } catch (e) {
    console.error('Error uploading files:', e);
  }
  return null;
}

/**
 * 获取底稿列表
 * @param params
 * @returns
 */
export async function getPaperList(params: {
  dbname: string;
  zcbfid: string;
  dgnd?: string;
  sjjd?: string;
}) {
  const res = await getApiData('sjdg.list', params);
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}
/**
 * 获取底稿统计数量，在状态上显示
 * @param params
 * @returns
 */
export async function getPaperCnt(params: {
  dbname: string;
  zcbfid: string;
  usercode: string;
  username?: string;
}) {
  const res = await getApiData('dgcheck.dgListCnt', params);
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}
/**
 * 获取底稿复核记录
 * @param params
 * @returns
 */
export async function getAuditPaperReViewList(params: {
  dbname: string;
  zcbfid: string;
  dgid: number;
}) {
  const res = await getApiData('dgcheck.fhList', params);
  if (res.ok) {
    const changeData = res.data.map((item: any) => {
      if (item.NextSpPerSon) {
        const newNextSpPerSon1 = item.NextSpPerSon.replace('(', '】');
        const newNextSpPerSon2 = `【${newNextSpPerSon1.replace(')', '')}`;
        item.NextSpPerSon = newNextSpPerSon2;
      }
      if (item.checkname) {
        const newCheckname1 = item.checkname.replace('(', '】');
        const newCheckname2 = `【${newCheckname1.replace(')', '')}`;
        item.checkname = newCheckname2;
      }
      return item;
    });
    return changeData;
  }
  message.error(res.data);
  return [];
}

/**
 * 打开 或 下载 底稿
 */
export async function getAuditPaper(params: {
  dbname: string;
  zcbfid: string;
  dgid: string;
  usercode?: string;
  type?: 'open' | 'down'; // 默认 down
}) {
  const r = await getApiData('pub.getViewDGinfo', params);
  if (r.ok) {
    const fileName = `${r.data[0].dgmc}${r.data[0].dglx}`;
    if (params.type === 'open') {
      openDG(JSON.stringify(r.data[0]));
      // openFile(r.data[0].url, fileName);
    } else {
      downloadDG(r.data[0].url, fileName);
    }
  } else {
    message.error(r.data);
  }
}
/**
 * 删除底稿，后期需要加入删除底稿文件的功能
 * @param params
 */
export async function delAuditPaper(params: {
  dbname: string;
  zcbfid: string;
  dgid: number | string; // 接受 整数的ID，和 dgnd+dgmc 字符串的ID
}) {
  const res = await getApiData('sjdg.deldg', params);
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}

/**
 * 获取审计阶段 列表 树
 * @param params
 * @returns
 */
export async function getAuditPhase(params: { dbname: string; zcbfid: string }): Promise<any> {
  const res = await getApiData('sjjd.tree', params);
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}

/**
 * 删除审计阶段
 * @param params
 */
export async function delAuditPhase(params: { dbname: string; partID: string; jdid: string }) {
  const r = await getApiData('sjjd.del', params);
  return Promise.resolve({
    data: r.data,
    success: r.ok,
  });
}

/**
 * 移动底稿/阶段到一个阶段下
 * @param dbName 数据名
 * @param zcbfID
 * @param jdid
 * @param data [] 底稿或阶段 id
 * @param type
 */
export async function moveToPhase(
  dbName: string,
  zcbfID: string,
  jdid: string,
  data: string[],
  type: 'dg' | 'jd',
) {
  const rows: {}[] = [];
  data.forEach((value) => {
    rows.push({
      rowState: 'update',
      pjdmc: jdid,
      where: {
        jdid: value,
      },
    });
  });
  const r = await getApiData('sqlApi.update', {
    dbName,
    name: type == 'dg' ? 'sjdg' : 'sjjd',
    rows,
  });
  return Promise.resolve({
    data: r.data,
    success: r.ok,
  });
}

// 移动接口底稿
export async function PaperMobile(
  type: string,
  distJDID: any,
  ids: any,
  sjxmbh: any,
  user: any,
  dbname: any,
): Promise<any> {
  const r = await request('/cpasApi/draftManage/moveStep', {
    method: 'POST',
    data: {
      type: type,
      distJDID: distJDID,
      ids: ids,
      sjxmbh: sjxmbh,
      user: user,
      dbname: dbname,
    },
  });
  return Promise.resolve({
    data: r.data,
    success: r.ok,
  });
}

// 新建 底稿
export async function getApiParperAdd(
  dbname: string,
  zcbfid: string,
  sjxmbh: any,
  jdid: string,
  dgnd: string,
  dgmcs: any,
  dgSyhs: any,
  mbName: any,
  user: any,
  rdgmcs: any = null,
  rdgsyh: any = null,
): Promise<any> {
  const res = await request('/cpasApi/draftManage/createDgByMbAndStep', {
    method: 'POST',
    data: {
      dgnd: dgnd,
      jdid: jdid,
      dgmcs: dgmcs,
      dgsyhs: dgSyhs,
      mbName: mbName,
      user: user,
      dbname: dbname,
      distPath: sjxmbh + '/' + zcbfid,
      rdgmcs,
      rdgsyh
    },
  });
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}

// 替换 底稿
export async function getApiParperReplace(
  dbname: string,
  zcbfid: string,
  sjxmbh: any,
  jdid: string,
  dgnd: string,
  dgmcs: any,
  dgsyhs: any,
  mbName: any,
  user: any,
): Promise<any> {
  const res = await request('/cpasApi/draftManage/replaceByMb', {
    method: 'POST',
    data: {
      dgnd: dgnd,
      jdid: jdid,
      dgmcs: dgmcs,
      mbName: mbName,
      dgsyhs,
      user: user,
      dbname: dbname,
      distPath: sjxmbh + '/' + zcbfid,
    },
  });
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}

// 清空底稿缓存
export async function clearDgCacheApi(folderPath?: string): Promise<any> {
  const res = await request('/cpasApi/draftManage/clearDgCache', {
    method: 'POST',
    data: {
      folderPath,
    },
  });
  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}

// 外部文件导入
export async function getPhaseTreeUpdate(
  user: any,
  dgnd: any,
  jdmc: any,
  sjxmbh: any,
  zcbfid: any,
  dbname: any,
  sourceFiles: any,
): Promise<any> {
  const res = await request('/cpasApi/draftManage/createDgByExternal', {
    method: 'POST',
    data: {
      user: user,
      dgnd: dgnd,
      jdmc: jdmc,
      dbname: dbname,
      distPath: sjxmbh + '/' + zcbfid,
      sourceFiles: sourceFiles,
    },
  });

  const params = {
    data: res.data,
    success: res.ok,
    errorList: res.data,
  };

  return Promise.resolve(params);
}

// 从模板库替换
export async function templateLibraryReplace(
  dbname: any,
  dgmc: string,
  mbmc: string,
  dgid: string,
  user: any,
  distPath: any,
): Promise<any> {
  const res = await request('/cpasApi/draftManage/replaceSingleByMb', {
    method: 'POST',
    data: {
      dbname: dbname,
      dgmc: dgmc,
      mbmc: mbmc,
      dgid: dgid,
      user: user,
      distPath: distPath,
    },
  });

  return Promise.resolve({
    data: res.data,
    success: res.ok,
  });
}
